package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.ColorBean;
import flc.ast.databinding.ActivityVideoBgBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoBgActivity extends BaseAc<ActivityVideoBgBinding> {

    public static String videoPath,outPath;
    private int oldPosition;
    private String bgColor="#FFFFFF";
    private List<ColorBean> listColor=new ArrayList<>();
    private ColorAdapter colorAdapter;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoSbLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideo.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_bg;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoBgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivGenerate.setOnClickListener(this);
        mDataBinding.tvDeriveVideo.setOnClickListener(this);
        mDataBinding.rvBgColorList.setLayoutManager(new GridLayoutManager(mContext,7));
        colorAdapter=new ColorAdapter();
        mDataBinding.rvBgColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivGenerate:
                videoBg();
                break;
            case R.id.tvDeriveVideo:
                saveVideo();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        bgColor=colorAdapter.getItem(position).getColor();
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition=position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);
    }

    @Override
    protected void initData() {
        //获取视频路径 时长
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        outPath=videoPath;
        //设置播放器
        setPlayer();
        listColor.add(new ColorBean("#FFFFFF", true));
        listColor.add(new ColorBean("#D8D8D8", false));
        listColor.add(new ColorBean("#2D2D2D", false));
        listColor.add(new ColorBean("#FF8F8F", false));
        listColor.add(new ColorBean("#FFBE46", false));
        listColor.add(new ColorBean("#FFEB47", false));
        listColor.add(new ColorBean("#9BDC3D", false));
        listColor.add(new ColorBean("#45C965", false));
        listColor.add(new ColorBean("#4FADB6", false));
        listColor.add(new ColorBean("#3C49DD", false));
        listColor.add(new ColorBean("#6140AA", false));
        listColor.add(new ColorBean("#C050DE", false));
        listColor.add(new ColorBean("#E74F8E", false));
        listColor.add(new ColorBean("#C82222", false));
        colorAdapter.setList(listColor);
    }

    private void videoBg(){
        String path = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_mp4));//输出路径
        EpEditor.insertBgColor(videoPath, 800, 1080, bgColor, path, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        outPath=path;
                        mDataBinding.videoView.setVideoPath(outPath);
                        mDataBinding.videoView.seekTo(1);
                        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
                        mDataBinding.videoView.start();
                        startTime();
                        ToastUtils.showShort(R.string.save_to_album);
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.add_bg_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                showDialog(getString(R.string.add_bg_ing)
                        + new DecimalFormat(getString(R.string.unit_num1)).format(progress * 100)
                        + getString(R.string.unit_percent));
            }
        });
    }

    //临时保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到相册
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, outPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        },500);
                    }
                });
            }
        }, 1000);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.sbVideo.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.tvVideoSbLeft.setText("00:00");
        mDataBinding.tvVideoSbRight.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoSbLeft.setText("00:00");
                mDataBinding.sbVideo.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang1);
                mp.seekTo(1);
                stopTime();
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting1);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }
}